import cv2
import io
import base64
import numpy as np
from PIL import Image


def image_to_base64(image_path):
    """
        将图片转为 Base64流
    :param image_path: 图片路径
    :return:
    """
    with open(image_path, "rb") as file:
        base64_data = base64.b64encode(file.read())  # base64编码
    return base64_data


def base64_to_image_cv(base64_data):
    """
        将 Base64流 转为 Opencv格式图片
    :param base64_data: base64编码
    :return: Opencv格式图片
    """
    img_b64decode = base64.b64decode(base64_data)  # base64解码
    img_array = np.fromstring(img_b64decode, np.uint8)  # 转换np序列
    img = cv2.imdecode(img_array, cv2.COLOR_BGR2RGB)  # 转换Opencv格式
    return img


def base64_to_image_PIL(base64_data):
    """
        将 Base64流 转为 PIL.Image格式图片
    :param base64_data: base64编码
    :return: PIL.Image格式图片
    """
    img_b64decode = base64.b64decode(base64_data)  # base64解码
    img = io.BytesIO(img_b64decode)
    img = Image.open(img)
    return img


if __name__ == '__main__':
    img_path = "/Users/zhanghao/Desktop/test.png"
    base64code = image_to_base64(img_path)
    print('完成=')
    print(base64code)
    with open('imagebase64.txt','wb') as fp:
        fp.write(base64code)

    #save_path = "../data/metric_save.jpg"
    # 保存 OpenCV格式
    # image = base64_to_image_cv(base64code)
    # cv2.imwrite(save_path, image)

    # 保存PIL格式
    #image = base64_to_image_PIL(base64code)
    #image.save(save_path)

